import autoexec_common
import log

def Startup(servicesToRun, startInline = [], serviceManagerClass = 'ServiceManager'):
    import blue
    blue.pyos.logMemory = 1
    args = blue.pyos.GetArg()[1:]
    autoexec_common.LogStarting('VaultGen')
    import nasty
    additionalScriptDirs = ['script:/../../../core/backend/script/', 'script:/../../backend/script/']
    for argument in args:
        if argument.startswith('-startOrchestrator'):
            additionalScriptDirs.extend(['script:/../../../core/orchestratorSlave/script/', 'script:/../../orchestratorSlave/script/'])
            SetupOrchestrator(argument.split(':'))
            servicesToRun.append('orchestratorSlave')
            break

    if ('/jessica' in args):
        additionalScriptDirs.extend(['script:/../../../../core_tools/MAIN/jessica/script/', 'script:/../../jessicaExtensions/script/'])
    nasty.Startup(additionalScriptDirs)
    import util
    import types
    print 'Nasty was started @ -',
    print strx(util.FmtTimeInterval((blue.os.GetTime(1) - nastyStarted)))
    t0 = blue.os.GetTime(1)
    t00 = t0
    import gc
    gc.disable()
    autoexec_common.LogStarted('VaultGen')
    for i in args:
        if ((i[0] != '-') and (i[0] != '/')):
            print 'Executing',
            print strx(i)
            blue.pyos.ExecFile(i, globals())

    import service
    smClass = getattr(service, serviceManagerClass)
    srvMng = smClass(startInline=(['DB2', 'machoNet'] + startInline))
    log.general.Log('Startup:  Starting Core Services...', log.LGNOTICE)
    print 'Core Services Starting @',
    print strx(util.FmtTimeInterval((blue.os.GetTime(1) - t0)))
    import svc
    svc.eveUserSvc.__dependencies__.remove('dogmaIM')
    svc.dustEveChat.__dependencies__.remove('LSC')
    startServices = ('machoNet', 'alert', 'objectCaching', 'debug', 'dust', 'dustBattle', 'miniFramework', 'dustInventory', 'dustDataLog', 'dustAccounting', 'dustEveChat')
    srvMng.Run(startServices)
    macho = sm.services['machoNet']
    DB2 = sm.services['DB2']
    dbzcluster = DB2.GetSchema('zcluster')
    dbzsystem = DB2.GetSchema('zsystem')
    while True:
        r = macho.AreTheseServicesRunning(startServices)
        if (r is None):
            break
        log.general.Log(('Startup:  Waiting for %s' % r), log.LGNOTICE)
        print 'Startup:  Waiting for',
        print strx(r)
        blue.pyos.synchro.Sleep(3000)

    print ('Database: ' + DB2.GetConnectionString())
    blue.os.SetAppTitle(('[%s %s.%s] %s %s %s.%s pid=%s' % (macho.GetNodeID(),
     macho.GetBasePortNumber(),
     boot.region.upper(),
     boot.codename,
     boot.role,
     boot.version,
     boot.build,
     blue.os.pid)))
    startupInfo = dbzcluster.Cluster_StartupInfo()[0]
    dbClusterMode = startupInfo.clusterMode
    if (dbClusterMode != prefs.clusterMode):
        log.Quit(('DB / Server disagree on cluster mode.  Server says %s, but DB says %s' % (prefs.clusterMode, dbClusterMode)))
        log.general.Log('###', log.LGERR)
        log.general.Log(('### ' + s), log.LGERR)
        log.general.Log('###', log.LGERR)
        log.Quit(s)
    print '...'
    log.general.Log('Server Configuration:', log.LGNOTICE)
    log.general.Log((' NodeID: %s' % macho.GetNodeID()), log.LGNOTICE)
    log.general.Log((' NodeName: %s' % macho.GetNodeName()), log.LGNOTICE)
    log.general.Log((' Base Port: %s' % macho.GetBasePortNumber()), log.LGNOTICE)
    log.general.Log((' Region: %s' % boot.region.upper()), log.LGNOTICE)
    log.general.Log((' CodeName: %s' % boot.codename), log.LGNOTICE)
    log.general.Log((' Role: %s' % boot.role), log.LGNOTICE)
    log.general.Log((' Version: %s.%s' % (boot.version, boot.build)), log.LGNOTICE)
    log.general.Log((' ProcessID: %s' % blue.os.pid), log.LGNOTICE)
    log.general.Log((' clusterMode: %s' % startupInfo.clusterMode), log.LGNOTICE)
    log.general.Log((' Host: %s' % blue.pyos.GetEnv().get('COMPUTERNAME', '?')), log.LGNOTICE)
    log.general.Log('Startup:  Synchronizing Clock with DB...', log.LGNOTICE)
    originalNow = blue.os.GetTime(1)
    timediff = 0
    for i in xrange(20):
        now1 = blue.os.GetTime(1)
        dbnow = dbzsystem.DateTime()[0].dateTime
        now2 = blue.os.GetTime(1)
        now = ((now1 + now2) / 2)
        if (abs((dbnow - now)) < ((i + 1) * const.SEC)):
            break
        reason = ('DB / Server time horribly out of synch, DB says now=%s but server thinks now=%s' % (util.FmtDate(dbnow), util.FmtDate(now)))
        log.general.Log(reason, 2)
        if (prefs.clusterMode != 'LIVE'):
            newnow = (dbnow + ((now2 - now1) / 2))
            log.general.Log(('Resetting clock, setting time: ' + util.FmtDate(newnow)), log.LGNOTICE)
            print 'Correcting clock to match DB ... advancing ',
            print (float((newnow - now2)) / float(const.SEC)),
            print ' secs'
            t0 += (newnow - now2)
            blue.pyos.synchro.ResetClock(newnow)
        elif (i < 10):
            log.general.Log('Retrying clock check to prevent node death', log.LGERR)
        else:
            continue
            log.Quit('DB / Server time horriby out of synch on live cluster.  Please perform a manual time synch.')

    finalNow = blue.os.GetTime(1)
    sm.ScatterEvent('OnTimeReset', originalNow, finalNow)
    nasty.nasty.OnTimeReset(originalNow, finalNow)
    log.general.Log('Startup:  Starting User Services...', log.LGNOTICE)
    print 'User Services Starting @',
    print strx(util.FmtTimeInterval((blue.os.GetTime(1) - t0)))
    srvMng.Run(servicesToRun)
    ram = ((blue.win32.GetProcessMemoryInfo()['PagefileUsage'] / 1024) / 1024)
    msg = ('Memory Usage (virtual mem) : %sMb upon startup' % ram)
    macho.LogWarn(msg)
    print msg



def StartServer(servicesToRun = [], startInline = [], serviceManagerClass = 'ServiceManager'):
    import blue
    t = blue.pyos.CreateTasklet(Startup, (servicesToRun,
     startInline,
     serviceManagerClass), {})
    t.context = '^boot::autoexec_server'


StartServer()

